using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using System.Diagnostics;

namespace The_LarX
{
    public class BasicPhysicsSystem : Component
    {
        public static BasicPhysicsSystem ActualPhysicsSystem;
        /// <summary>
        /// A Gravidade
        /// </summary>
        public Vector2 Gravity;

        /// <summary>
        /// As Sprites que estamos utilizando
        /// </summary>
        public List<PhysicBody> Bodies;

        public float MinCol = 0.05f;

        public BasicPhysicsSystem(GameScreen Parent)
            : base(Parent)
        {
            ActualPhysicsSystem = this;
            Load();
        }
        public BasicPhysicsSystem()
        {
            ActualPhysicsSystem = this;
            Load();
        }
        public void Load()
        {
            Bodies = new List<PhysicBody>();

            Gravity = new Vector2(0, 5);
        }

        public override void Update()
        {
            for (int j = 0; j < Bodies.Count; j++)
            {
                if (!Bodies[j].Immovable)
                {
                    Bodies[j].Collisions.Clear();
                    ApplyForces(Bodies[j]);

                    for (int k = 0; k < Bodies.Count; k++)
                    {
                        if (k != j)
                        {
                            CheckForces(Bodies[j], Bodies[k]);                                                
                        }
                    }                    
                }
            }

            base.Update();
        }

        public void ApplyForces(PhysicBody Body)
        {
            if (!Body.Immovable)
            {
                Body.Velocity += Gravity;
            }
        }
        public void CheckForces(PhysicBody Body, PhysicBody BodyTwo)
        {
            if (Body.Rectangle.Intersects(BodyTwo.Rectangle))
            {
                Body.Collisions.Add(BodyTwo);
                Vector2 pos = Body.Position - BodyTwo.Position;
                Vector2 npos = Vector2.Normalize(pos);
               
                if (npos.Y < MinCol)
                {
                    Body.Velocity.Y -= Gravity.Y;
                }
                Debug.WriteLine(npos);
                //Body.Velocity -= Vector2.Normalize(BodyTwo.Position) * Gravity * 1.01f;              
            }       
        }

        public override void Draw()
        {
            base.Draw();
        }
    }
}
